React components should not be nested, as their state will be lost on each re-render of their parent component, possibly introducing bugs. This
will also impact performance as child components will be recreated unnecessarily.
If the goal is to have the state reset, use a key
instead of relying on a parent
state.
function Component() {
function NestedComponent() { // Noncompliant: NestedComponent should be moved outside Component
return <div />;
}
return (
<div>
<NestedComponent />
</div>
);
}
function Component() {
return (
<div>
<OtherComponent footer={ () => <div /> } /> { /* Noncompliant: Component is created inside prop */ }
</div>
);
}
class Component extends React.Component {
render() {
function UnstableNestedComponent() { // Noncompliant: NestedComponent should be moved outside Component
return <div />;
}
return (
<div>
<UnstableNestedComponent />
</div>
);
}
}
You should refactor your code to define a component independently, passing props if needed.
function OutsideComponent(props) {
return <div />;
}
function Component() {
return (
<div>
<OutsideComponent />
</div>
);
}
function Component() {
return <OtherComponent footer={ <div /> } />;
}
class Component extends React.Component {
render() {
return (
<div>
<OtherComponent />
</div>
);
}
}
Component creation is allowed inside component props only if prop name starts with render
. Make sure you are calling the prop in the
receiving component and not using it as an element.
function OtherComponent(props) {
return <div>{props.renderFooter()}</div>;
}
function Component() {
return (
<div>
<OtherComponent renderFooter={() => <div />} />
</div>
);
}